package com.jintoufs.web.action.quartz;

import com.jintoufs.domain.constants.Constants;
import com.jintoufs.service.baseinfo.CoinService;
import com.jintoufs.service.baseinfo.MarketService;
import com.jintoufs.service.baseinfo.SiteService;
import com.jintoufs.util.DyMethodUtil;
import com.jintoufs.web.action.support.SupportAction;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author xiaoemo
 * 获取市场价格
 */
@Controller
@Scope("prototype")
@RequestMapping("/site")
public class MarketQuartzAction extends SupportAction {
    @Resource
    private SiteService siteService;
    @Resource
    private CoinService coinService;
    @Resource
    private MarketService marketService;

    //创建线程池
    private ExecutorService executorService = Executors.newFixedThreadPool(10);//创建一个100根线程的线程池

    /**
     * 定时获取API数据任务
     */
    public void quartzTask() throws Exception {

        executorService.execute(new Runnable() {
            public void run() {
                Map<String, Object> params = new HashMap();
                params.put("status", Constants.SITE_STATUS_1);
                List<Map<String, Object>> sites = siteService.queryByParams(params);
                if (sites.isEmpty()) {
                    return;
                }

                // 循环取得所有启用的网站
                for (Map<String, Object> site : sites) {
                    Integer siteId = Integer.parseInt(site.get("id").toString());

                    Map<String, Object> paramsCoin = new HashMap();
                    paramsCoin.put("siteId", siteId);
                    List<Map<String, Object>> coins = coinService.querySiteCoinByParams(paramsCoin);
                    if (coins.isEmpty()) {
                        continue;
                    }

                    parseListJson(site, coins);
                }
            }

        });
    }

    private void parseListJson(Map<String, Object> site, List<Map<String, Object>> coins) {
        Map<String, Object> map = new HashMap<String, Object>();
        String siteName = site.get("site_name").toString();
        map.put("site", site);
        map.put("coins", coins);
        map.put("marketService", marketService);
        DyMethodUtil.invokeMethod("marketService." + siteName + "(site,coins)", map);
    }

}
